﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using DevExtreme.AspNet.Data;
using Microsoft.EntityFrameworkCore;
using Leo.Core.Domain;
using Newtonsoft.Json;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Leo.Core.EntityFrameworkCore
{
    public abstract class BaseEFCoreAbpRepository<TDbContext, TEntity, TKey> : EfCoreRepository<TDbContext, TEntity, TKey>
                                                                          , IBaseAbpRepository<TEntity, TKey>
        where TDbContext : IEfCoreDbContext
        where TKey : struct
        where TEntity : class, IEntity<TKey>
    {
        protected BaseEFCoreAbpRepository(IDbContextProvider<TDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        protected async Task<TEntity> Find(Func<TEntity, bool> predicate)
        {
            var query = await GetQueryableAsync();

            var queryResult = query.Where(predicate);

            return queryResult.FirstOrDefault();
        }

        protected async Task<List<TEntity>> FindAll(Func<TEntity, bool> predicate)
        {
            var query = await GetQueryableAsync();

            var queryResult = query.Where(predicate);

            return queryResult.ToList();
        }

        protected async Task<bool> Existed(Func<TEntity, bool> predicate)
        {
            var entity = await Find(predicate);

            return entity != null;
        }

        protected async Task<int> Count(Func<TEntity, bool> predicate)
        {
            var query = await GetQueryableAsync();

            var queryResult = query.Where(predicate);

            return queryResult.Count();
        }

        /// <summary>
        /// dev组件修改方法
        /// </summary>
        /// <param name="key"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public async Task<TEntity> DevUpdateAsync(TKey key, string values)
        {
            var entity = await (await GetDbSetAsync()).FirstOrDefaultAsync(t => t.Id.Equals(key));
            JsonConvert.PopulateObject(values, entity);
            await UpdateAsync(entity);
            return entity;
        }

        /// <summary>
        /// dev组件查询方法
        /// </summary>
        /// <param name="loadOptions"></param>
        /// <returns></returns>
        public async Task<object> GetDevListAsync(DataSourceLoadOptionsBase loadOptions)
        {
            return DataSourceLoader.Load(await GetQueryableAsync(), loadOptions);
        }
    }
}
